﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Office.Interop.Word;
using System.Data;

namespace CExcelOp
{
    public class BaseWord
    {
        Microsoft.Office.Interop.Word.Application app;
        Document doc;
        /// <summary>
        /// 打开Word文件
        /// </summary>
        /// <param name="fileName">模板位置及名称</param>
        /// <returns></returns>
        public bool Open(string fileName,bool isVisible=false)
        {
            try
            {
                app = new Microsoft.Office.Interop.Word.Application();//打开word程序
                doc = new Document();//创建word对象
                object unknow = Type.Missing;
                object File = fileName;
                app.Visible = isVisible;//设置word程序可见
                doc = app.Documents.Open(ref File,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow,
                ref unknow, ref unknow, ref unknow, ref unknow, ref unknow);//打开word文档
                return true;
            }
            catch
            {
                return false;
            }
        }
        public void Close()
        {
            doc.Close();
            app.Quit();
            GC.Collect();
        }
       
        /// <summary>
        /// 向书签里写字
        /// </summary>
        /// <param name="name"></param>
        /// <param name="value"></param>
        public void SetBookMarksValue(object name, string value)
        {
            doc.Bookmarks.get_Item(ref name).Range.Text = value;
        }
        public void SetBookBooksValue(System.Data.DataTable dt)
        {
            foreach (Microsoft.Office.Interop.Word.Bookmark bm in doc.Bookmarks)
            {
                if (dt.Columns.Contains(bm.Name))
                {
                    SetBookMarksValue(bm.Name, dt.Rows[0][bm.Name].ToString());
                }
            }
        }
    }
}
